<?php
namespace app\index\controller\dictionary;
use app\index\controller\BaseIndex;
use szktor\ClinicDict; //诊所门店公共字典
use app\common\model\ClinicDictsheet; //字典表数据

/*
* 前台-字典维护 -> 诊疗项目
* index/dictionary.zhenliao/index
*/
class Zhenliao extends BaseIndex
{
    protected $noNeedLogin = [];  //无需登录的方法，同时也就不需要鉴权了
    protected $noNeedRight = ['info','del','get_newbianma']; //无需鉴权的方法，但需要登录
    protected $zlxmUnitList = []; //诊疗项目单位
    protected $zlxmCateList = []; //诊疗项目分类

    //初始化
    public function initialize()
    {
        parent::initialize();
        //诊疗项目单位
        $this->zlxmUnitList = ClinicDictsheet::getDictList('zlxmunit',$this->admin['clinic_id'],'id,name');
        //诊疗项目分类
        $this->zlxmCateList = ClinicDictsheet::getDictList('zlxmcate',$this->admin['clinic_id'],'id,name');
    }

    //首页
    public function index()
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            try
            {
                $data = $this->request->only(['dicttype','keyword','status','page'],'post');
                if(!isset($data['dicttype']))
                {
                    return json(['code' => '1', 'msg' => '参数错误，无法获取数据', 'count' => '0', 'data' => []]);
                }
                $data['dicttype'] = strtolower($data['dicttype']);
                //获取列表
                return $this->getZhenLiaoList($data);
            }catch (\think\Exception $e){ // use think\Exception;
                return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
            }
        }
		$this->assign([
            'zlxm_cate_list' => $this->zlxmCateList, //诊疗项目分类列表
            'zlxm_unit_list' => $this->zlxmUnitList, //诊疗项目单位
        ]);
        return $this->view->fetch();
    }
    //修改 + 新增
    public function info()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            //修改+新增
            return $this->getZhenLiaoListInfo();
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }
    //删除
    public function del()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $r = false;
            $map = [['id','in',$data['id']],['clinic_id','=',$this->admin['clinic_id']]];
            //字典表数据_通用
            $r = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_zhenliao')->where($map)->delete();
            if(!$r) return json(['err' => '2', 'msg' => '删除失败，请重试']);
            return json(['err' => '0', 'msg' => '删除成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }
    //获取列表
    private function getZhenLiaoList($post)
    {
        //条件
        $map = [['clinic_id','=', $this->admin['clinic_id']]];
        $page = isset($post['page']) ? $post['page'] : 1;
        if(isset($post['dicttype']) && $post['dicttype'] != '')
        {
            if(strtoupper($post['dicttype']) != 'ALL')
            {
                $map[] = ['cate_id','=',$post['dicttype']];
            }
        }
        if(isset($post['keyword']) && $post['keyword'] != '')
        {
            $map[] = ['name|bianma|py_code|wb_code','like','%' . $post['keyword'] . '%'];
        }
        if(isset($post['status']) && $post['status'] != '')
        {
            if(strtoupper($post['status']) != 'ALL') $map[] = ['status','=',(int)$post['status']];
        }
        $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
        $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_zhenliao')->where($map)->field('*')
                ->order('create_time desc')->paginate($limit,false,['page' => $page, 'var_page' => 'page']);
        if (count($list) <= 0) {
            return json(['code' => '1', 'msg' => '当前页下的数据已显示完毕！', 'count' => '0', 'data' => []]);
        }
        $res = ['code' => 0,'msg' => '', 'count' => $list->total(), 'data' => $list->items()];
        foreach ($res['data'] as $key => &$val) {
            $val['ls_unit_txt'] = _getDictNameTxt($val['ls_unit'],$this->zlxmUnitList);
            $val['create_time'] = $val['create_time'] > 0 ? date('Y-m-d Hi:s') : '';
        }
        return json($res);
    }

    //修改+新增
    private function getZhenLiaoListInfo()
    {
        $data = $this->request->only([
            'dicttype','id','bianma','name','ls_unit','price','cate_id','py_code','wb_code',
            'remarks','xm_tc_mode','xm_tc_val','is_mz_tj','status',
        ],'post');
        if(!isset($data['id']))
        {
            return json(['err' => '1', 'msg' => '参数错误，无法执行']);
        }
        $dictType = strtolower($data['dicttype']);
        if(!isset($data['name']) || $data['name'] == '')
        {
            return json(['err' => '2', 'msg' => '必须输入一个名称']);
        }
       if(!isset($data['price']) || $data['price'] == '')
        {
            return json(['err' => '4', 'msg' => '请输入项目单价']);
        }
        try
        {
            $info = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_zhenliao')->where(['id' => intval($data['id']), 'clinic_id' => $this->admin['clinic_id']])->find();
            if($info) //数据已存在
            {
                unset($data['dicttype'],$data['id']);
                $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_zhenliao')->where(['id' => $info['id']])->update($data);
            }else{ //数据不存在
                unset($data['dicttype'],$data['id']);
                $sqlData = array_merge($data,[
                    'clinic_id' => $this->admin['clinic_id'], //诊所门店表的id
                    'create_time' => time(), //创建时间
                ]);
                $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_zhenliao')->insertGetId($sqlData);
            }
            unset($info,$sqlData);
            if(!$editRes) return json(['err' => '2', 'msg' => '诊疗项目数据保存失败']);
            return json(['err' => '0', 'msg' => '诊疗项目数据已保存成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '失败：' . $e->getMessage()]);
        }
    }
 
    //生成一个新的项目编码
    public function get_newbianma()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $newBianMa = date('Ym') . rand(1000,9999);
            return json(['err' => '0', 'msg' => '成功', 'data' => $newBianMa]);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }
}
